#include "Page.h"
#include <cstring>
#include <iostream>

namespace MiniDB
{

    Page::Page(int page_id, PageType type)
        : page_id_(page_id), page_type_(type), is_dirty_(false),
          pin_count_(0), used_space_(0)
    {
        data_.fill(0); // Initialize page data to zero
    }

    bool Page::writeData(size_t offset, const void *data, size_t size)
    {
        if (offset + size > PAGE_SIZE)
        {
            std::cerr << "Error: Write operation exceeds page boundary" << std::endl;
            return false;
        }

        std::memcpy(data_.data() + offset, data, size);

        // Update used space if writing beyond current used space
        size_t end_offset = offset + size;
        if (end_offset > used_space_)
        {
            used_space_ = end_offset;
        }

        markDirty();
        return true;
    }

    bool Page::readData(size_t offset, void *buffer, size_t size) const
    {
        if (offset + size > PAGE_SIZE)
        {
            std::cerr << "Error: Read operation exceeds page boundary" << std::endl;
            return false;
        }

        std::memcpy(buffer, data_.data() + offset, size);
        return true;
    }

    void Page::clear()
    {
        data_.fill(0);
        used_space_ = 0;
        markClean();
    }

} // namespace MiniDB
